import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
import NProgress from 'nprogress'
import Cookies from 'js-cookie'
import 'nprogress/nprogress.css'

Vue.use(Router)

const LOGIN_PAGE_NAME = 'login'

const router = new Router({
  routes
})

router.beforeEach(async (to, form, next) => {
  NProgress.start()
  const token = Cookies.get('token')
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面是登录页
    next()
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录 且要跳转的页面是登录页 跳转到home页
    next({ name: 'Home' })
  } else {
    next()
  }
})

router.afterEach(to => {
  NProgress.done()
})

export default router
